package com.shuorikeji.huohuo.ui.me;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.android.material.imageview.ShapeableImageView;
import com.shuorikeji.huohuo.R;
import com.shuorikeji.huohuo.base.BasePresenterActivity;
import com.shuorikeji.huohuo.bean.UserInfoBean;
import com.shuorikeji.huohuo.bean.UserInfoMainBean;
import com.shuorikeji.huohuo.callback.ClickCallBack;
import com.shuorikeji.huohuo.common.Constant;
import com.shuorikeji.huohuo.mvp.AllPresenter;
import com.shuorikeji.huohuo.utils.BusinessUtils;
import com.shuorikeji.huohuo.utils.DialogUtil;
import com.shuorikeji.huohuo.utils.GlideLoadEngine;
import com.shuorikeji.huohuo.utils.JsonUtil;
import com.shuorikeji.huohuo.utils.PreUtils;
import com.shuorikeji.huohuo.utils.ToastShowUtil;
import com.luck.picture.lib.permissions.RxPermissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.filter.Filter;
import com.zhihu.matisse.internal.entity.CaptureStrategy;
import com.zhihu.matisse.internal.entity.IncapableCause;
import com.zhihu.matisse.internal.entity.Item;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import androidx.annotation.Nullable;
import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class XgUserInfoActivity extends BasePresenterActivity<AllPresenter> {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.siv_tx)
    ShapeableImageView sivTx;
    @BindView(R.id.tv_nc)
    TextView tvNc;
    @BindView(R.id.tv_id)
    TextView tvId;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.rl_nc)
    RelativeLayout rlNc;

    private UserInfoBean userInfoBean;
    private List<String> imgLocalList = new ArrayList<>();
    private List<String> imgNetList = new ArrayList<>();
    private String imgNetUrl = "";
    private Dialog xgNcDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getmImmersionBar().reset().statusBarColor(R.color.transparent).statusBarDarkFont(true, 0.2f).init();
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_xg_user_info);
    }

    @Override
    protected void initData() {
        userInfoBean = BusinessUtils.getUserInfo();
        showUserInfo();
        initClick();
    }

    private void showUserInfo() {
        try {
            if (userInfoBean != null) {
                BusinessUtils.setLoadImg(XgUserInfoActivity.this, userInfoBean.getAvatar(), R.mipmap.icon_my_default_tx, sivTx);
                tvNc.setText(userInfoBean.getNickname());
                tvId.setText(String.valueOf(userInfoBean.getUser_id()));
                tvPhone.setText(userInfoBean.getMobile());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void rqTxQx(int code) {
        final String[] permissionsGroup = new String[]{
                Manifest.permission.CAMERA
                , Manifest.permission.WRITE_EXTERNAL_STORAGE
                , Manifest.permission.READ_EXTERNAL_STORAGE};
        new RxPermissions(this)
                .request(permissionsGroup)
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(Boolean aBoolean) {
                        Log.i("wxl", "上传头像权限申请状态：" + aBoolean);
                        if (aBoolean) {
                            secTxPhoto(code);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    private void secTxPhoto(int qxCode) {
        Matisse.from(this)
                .choose(MimeType.ofImage(), false)
                .capture(true)  // 使用相机，和 captureStrategy 一起使用
                .captureStrategy(new CaptureStrategy(true, "com.ld.music.fileprovider"))
                .theme(R.style.Matisse_Dracula)
                .countable(true)
                .maxSelectable(1)
                .addFilter(new Filter() {
                    @Override
                    protected Set<MimeType> constraintTypes() {
                        return new HashSet<MimeType>() {{
                            add(MimeType.PNG);
                        }};
                    }

                    @Override
                    public IncapableCause filter(Context context, Item item) {
                        try {
                            InputStream inputStream = getContentResolver().openInputStream(item.getContentUri());
                            BitmapFactory.Options options = new BitmapFactory.Options();
                            options.inJustDecodeBounds = true;
                            BitmapFactory.decodeStream(inputStream, null, options);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }
                })
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                .thumbnailScale(0.87f)
                .imageEngine(new GlideLoadEngine())
                .forResult(qxCode);
    }

    private void scPhoto() {
        BusinessUtils.upLoadPhotos(imgLocalList, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        imgNetList.clear();
                        imgNetList = (List<String>) object;
                        imgNetUrl = imgNetList.get(0);
                        xgUserInfo(imgNetUrl, userInfoBean.getNickname());
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(XgUserInfoActivity.this, msg);
                        break;
                }
            }
        });
    }

    private void xgUserInfo(String txUrl, String ncContent) {
        mPresenter.xgUserInfo(true, txUrl, ncContent, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        ToastShowUtil.showToastCenter(XgUserInfoActivity.this, "修改成功");
                        getUserInfo();
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(XgUserInfoActivity.this, msg);
                        break;
                }
            }
        });
    }

    private void getUserInfo() {
        mPresenter.getUserInfo(false, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        UserInfoMainBean data = (UserInfoMainBean) object;
                        PreUtils.put(Constant.LOGIN_USER_INFO, JsonUtil.toJson(data.getData()));
                        userInfoBean = data.getData();
                        showUserInfo();
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(XgUserInfoActivity.this, msg);
                        break;
                }
            }
        });
    }

    private void xgNcDialog() {
        xgNcDialog = DialogUtil.showXgNcDialog(XgUserInfoActivity.this, userInfoBean.getNickname(), new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(XgUserInfoActivity.this, msg);
                        break;
                    case 2:
                        String content = (String) object;
                        xgUserInfo(userInfoBean.getAvatar(), content);
                        break;
                }
            }
        });
    }

    private void initClick() {
        ivBack.setOnClickListener(view -> {
            finish();
        });
        sivTx.setOnClickListener(view -> {
            rqTxQx(1001);
        });
        rlNc.setOnClickListener(view -> {
            xgNcDialog();
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            List<String> pathList = Matisse.obtainPathResult(data);
            switch (requestCode) {
                case 1001:
                    for (String pathTemp : pathList) {
                        Log.i("wxl", "上传用户头像选择的图片path：" + pathTemp);
                        imgLocalList.clear();
                        imgLocalList.add(pathTemp);
                        scPhoto();
                    }
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BusinessUtils.clearDialog(xgNcDialog);
    }
}